/*
 * Filename:  SafeDao.java
 * Copyright:  Raisecom Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * Description:  <description>
 * Author:  donghu
 * Edit-time:  2016-5-4
 * Modify content:  <modify content>
 */
package com.gutetec.cms.usmc.db.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gutetec.cms.usmc.bean.UserInfo;
import com.gutetec.cms.usmc.util.UsmcUtil;

/**
 * <Database operation>
 * <Function details>
 * @author  donghu
 * @version  [Version, 2016-5-4]
 * @see  [Classs/Method]
 * @since  [Product/Model Version]
 */
public class UserDao extends UsmcDbDao<UserInfo>
{
    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);
    
    private final SessionFactory sessionFactory;
    
    /**
     * 
     * <Constructor>
     */
    public UserDao(SessionFactory sessionFactory)
    {
        super(sessionFactory);
        this.sessionFactory = sessionFactory;
    }
    
    /**
     * {@inheritDoc}
     */
    protected Session currentSession()
    {
        return sessionFactory.getCurrentSession();
    }
    
    /**
     * find all
     * <find all user info>
     * @return
     * @see [class]
     */
    public List<UserInfo> findAll()
    {
        List<UserInfo> result = null;
        try
        {
            beginTransaction();
            result = list(session.createQuery("FROM UserInfo user"));
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        return result;
    }
    
    /**
     * find by pages
     * <find user info by page>
     * @return
     * @see [class]
     */
    @SuppressWarnings("unchecked")
    public List<UserInfo> findByPage(int pageSize, int page)
    {
        List<UserInfo> result = null;
        try
        {
            beginTransaction();
            String hql =
                "FROM UserInfo user WHERE user.userName<>'root' and user.userName<>'raisecom' order by user.userAccountTime desc";    
            Query query = session.createQuery(hql);
            query.setFirstResult(page);
            query.setMaxResults(pageSize);
            result = (List<UserInfo>)query.list();
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        return result;
    }
    
    /**
     * get user info count
     * <get user info count>
     * @return
     * @see [class]
     */
    @SuppressWarnings("unchecked")
    public int getUserByNameNum(String name)
    {
        List<UserInfo> result = null;
        int totalRows = 0;
        try
        {
            beginTransaction();
            String hql =
                "FROM UserInfo user WHERE user.userName<>'root' and user.userName<>'raisecom' and user.userName like :userName order by user.userAccountTime desc";
            result = (List<UserInfo>)session.createQuery(hql).setParameter("userName", "%" + name + "%").list();
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        totalRows = result.size();
        return totalRows;
    }
    
    /**
     * find by name
     * <find user info by name>
     * @return
     * @see [class]
     */
    @SuppressWarnings("unchecked")
    public List<UserInfo> findByName(int pageSize, int page, String name)
    {
        List<UserInfo> result = null;
        try
        {
            beginTransaction();
            Query query = null;
            String hql = "";
            if (UsmcUtil.isEmpty(name))
            {
                hql =
                    "FROM UserInfo user WHERE user.userName<>'root' and user.userName<>'raisecom' order by user.userAccountTime desc"; 
                query = session.createQuery(hql);
            }
            else
            {
                hql =
                    "FROM UserInfo user WHERE user.userName<>'root' and user.userName<>'raisecom' and user.userName like :userName order by user.userAccountTime desc";    
                query = session.createQuery(hql).setParameter("userName", "%" + name + "%");
            }
            query.setFirstResult(page);
            query.setMaxResults(pageSize);
            result = (List<UserInfo>)query.list();
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        return result;
    }
    
    /**
     * get user info count
     * <get user info count>
     * @return
     * @see [class]
     */
    @SuppressWarnings("unchecked")
    public int getUserNum()
    {
        List<UserInfo> result = null;
        int totalRows = 0;
        try
        {
            beginTransaction();
            result =
                (List<UserInfo>)session.createQuery("SELECT user FROM UserInfo user WHERE user.userName<>'root' and user.userName<>'raisecom'")
                    .list();
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        totalRows = result.size();
        return totalRows;
    }
    
    /**
     * get user info by ID
     * < get user info by ID>
     * @param id
     * @return
     * @see [class]
     */
    public UserInfo findById(long id)
    {
        List<UserInfo> resultList = null;
        UserInfo result = new UserInfo();
        try
        {
            beginTransaction();
            resultList = list(session.createQuery("FROM UserInfo user WHERE userID =:id")
                .setParameter("id", id));
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        
        if (resultList.size() != 0)
        {
            result = resultList.get(0);
            return result;
        }
        else
        {
            return null;
        }
    }
    
    /**
     * get user info by IP address
     * <get user info by IP address>
     * @param UserIpAddr
     * @return
     * @see [class]
     */
    public UserInfo findByIP(String UserIpAddr)
    {
        List<UserInfo> resultList = null;
        UserInfo result = new UserInfo();
        try
        {
            beginTransaction();
            resultList = list(session
                .createQuery(
                    "FROM UserInfo user WHERE userSafeAddress =:UserIpAddr")
                .setParameter("UserIpAddr", UserIpAddr));
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        
        if (resultList.size() != 0)
        {
            result = resultList.get(0);
            return result;
        }
        else
        {
            return null;
        }
    }
    
    /**
     * add user info
     * <add user info>
     * @param currentUser
     * @return
     * @see [class]
     */
    public boolean save(UserInfo currentUser)
    {
        try
        {
            beginTransaction();
            session.save(currentUser);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * update user info
     * <update user info>
     * @param curUser
     * @return
     * @see [class]
     */
    public boolean update(UserInfo curUser)
    {
        try
        {
            beginTransaction();
            session.update(curUser);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * <modify user info>
     * <Detailed description of function>
     * @param curUser
     * @return
     * @see [class、function]
     */
    public boolean modifyUserInfo(UserInfo curUser)
    {
        try
        {
            beginTransaction();
            StringBuilder hql = new StringBuilder("update UserInfo info set ");
            hql.append("userPhone ='"); 
            hql.append(curUser.getUserPhone());
            hql.append("', userMailbox='");
            hql.append(curUser.getUserMailbox());
            hql.append("', userSafeAddress='");
            hql.append(curUser.getUserSafeAddress());
            hql.append("'");
            
            if (!UsmcUtil.isEmpty(curUser.getUserRole()))
            {
                hql.append(", userRole=");
                hql.append(Integer.parseInt(curUser.getUserRole()));
            }
            
            if (!UsmcUtil.isEmpty(curUser.getUserSafeState()))
            {
                hql.append(", userSafeState=");
                hql.append(Integer.parseInt(curUser.getUserSafeState()));
            }
            
            if (!UsmcUtil.isEmpty(curUser.getUserExpiryDateCount()))
            {
                hql.append(", userExpiryDateCount=");
                hql.append(Integer.parseInt(curUser.getUserExpiryDateCount()));
            }
            
            if (!UsmcUtil.isEmpty(curUser.getUserPassExpiryDateCount()))
            {
                hql.append(", userPassExpiryDateCount=");
                hql.append(Integer.parseInt(curUser.getUserPassExpiryDateCount()));
            }
            
            if (!UsmcUtil.isEmpty(curUser.getUserSessionTime()))
            {
                hql.append(", userSessionTime=");
                hql.append(Integer.parseInt(curUser.getUserSessionTime()));
            }
            
            hql.append(" WHERE userID ='");
            hql.append(curUser.getUserID());
            hql.append("'");
            
            Query query = session.createQuery(hql.toString());
            query.executeUpdate();
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * update user info by user IP address
     * <update user info by user IP address>
     * @param IpAddr
     * @param state
     * @return
     * @see [class]
     */
    public boolean updateUserStateByIP(String IpAddr, int state)
    {
        try
        {
            beginTransaction();
            Query query = session.createQuery("update UserInfo user set userSafeState =? where userSafeAddress =?");
            query.setInteger(0, state);
            query.setString(1, IpAddr);
            query.executeUpdate();
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * delete user info
     * <delete user info>
     * @param curUser
     * @return
     * @see [class]
     */
    public boolean delete(UserInfo curUser)
    {
        try
        {
            beginTransaction();
            session.delete(curUser);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * delete user info by ID
     * <delete user info by ID >
     * @param ids
     * @return
     * @see [class]
     */
    public boolean deleteUsersById(List<?> ids)
    {
        String hql = "delete UserInfo user where userID IN (:ids)";
        try
        {
            beginTransaction();
            Query query = session.createQuery(hql);
            query.setParameterList("ids", ids);
            query.executeUpdate();
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
            return false;
        }
        finally
        {
            closeTransaction();
        }
        return true;
    }
    
    /**
     * is user exist
     * <is User Exist >
     * @param ids
     * @return true: not exist,false: exist
     * @see [class]
     */
    public boolean isUserExist(String userName)
    {
        List<UserInfo> resultList = null;
        try
        {
            beginTransaction();
            /* Modify MANTIS:0005862 Begin*/
            /*
            resultList = list(session
                .createQuery(
                    "FROM UserInfo info WHERE userName =:userName")
                .setParameter("userName", userName));
           */
            String sql = "select * from user where binary userName =" + "\"" + userName + "\"";
            resultList = list(session.createSQLQuery(sql));
           /* Modify MANTIS:0005862 End*/
        }
        catch (HibernateException e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        
        if (resultList.size() != 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
}
